package com.liufeng.myheart.login;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.baidu.trace.OnEntityListener;
import com.liufeng.myheart.MapActivity;
import com.liufeng.myheart.MyApplication;
import com.liufeng.myheart.R;
import com.liufeng.myheart.model.StatusData;
import com.liufeng.myheart.util.GsonService;
import com.liufeng.myheart.util.TraceUtil;

/**
 * Created by liufeng on 2016/7/13.
 */
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText phoneText;
    private Button loginBtn;
    SharedPreferences myspf;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        setTitle("登录");
        phoneText= (EditText) findViewById(R.id.phone);
        loginBtn= (Button) findViewById(R.id.login);
        loginBtn.setOnClickListener(this);
        myspf = getSharedPreferences("myheart",
                Context.MODE_PRIVATE);
        String my=myspf.getString("my","");
        if(!my.isEmpty()){
            goToMap();
        }
    }

    private void goToMap() {
        Intent intent=new Intent(LoginActivity.this, MapActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    public void onClick(View view) {
        if(view.getId()==R.id.login){
            final String phone=phoneText.getText().toString();
            if(phone.isEmpty()){
                Toast.makeText(LoginActivity.this,"请填写手机号码.",Toast.LENGTH_SHORT).show();
                return;
            }else{
                TraceUtil.addEntity(phone, new OnEntityListener() {
                    @Override
                    public void onRequestFailedCallback(String s) {
                        Toast.makeText(LoginActivity.this,"登录失败,请稍后重试.",Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onAddEntityCallback(String s) {
                        StatusData statusData = GsonService.parseJson(s, StatusData.class);
                        if(statusData.getStatus()==0||statusData.getStatus()==3005){
                            SharedPreferences.Editor edit = myspf.edit();
                            edit.putString("my",phone);
                            edit.commit();
                            goToMap();
                        }
                    }
                });
            }
        }
    }
}
